//
//  RegisterViewController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/4.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import YYText
import TOWebViewController
import Alamofire
class RegisterNavigation: UINavigationController {
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nil, bundle: nil)
    }
    
    init() {
        let vc = RegisterViewController()
        super.init(rootViewController: vc)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

class RegisterViewController: UIViewController {
    fileprivate var beenRegister:Bool?
    fileprivate lazy var reRegisterView:TWLAlertView = {
        let reRegisterView = TWLAlertView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        let securityView = HaveBeenRegisterView.init(frame: CGRect(x: 0, y: 0, width: 271, height: 157))
        securityView.popBackButton.addTarget(self, action: #selector(self.popButtonClick), for: .touchUpInside)
        securityView.reRegisterButton.addTarget(self, action: #selector(self.reRegisterClick), for: .touchUpInside)
        reRegisterView.initWithCustomView(securityView, frame: CGRect(x: 0, y: 0, width: 271, height: 157))
        return reRegisterView
    }()
    
    var phoneNumberTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入手机号码"
        textField.keyboardType = .phonePad
        textField.clearButtonMode = .always
        let imageView = UIImageView(image: UIImage.init(named: "ic_account_circle")!.withRenderingMode(.alwaysTemplate))
        imageView.tintColor = UIColor.gray
        imageView.frame = CGRect(x: 0, y: 0, width: 38, height: 24)
        imageView.contentMode = .scaleAspectFit
        textField.leftView = imageView
        textField.leftViewMode = .always
        
        return textField
    }()
    
    var securityTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入短信验证码"
        textField.keyboardType = .phonePad
        
        let imageView = UIImageView(image: UIImage.init(named: "reply_n")!.withRenderingMode(.alwaysTemplate))
        imageView.tintColor = UIColor.gray
        imageView.frame = CGRect(x: 0, y: 0, width: 38, height: 24)
        imageView.contentMode = .scaleAspectFit
        textField.leftView = imageView
        textField.leftViewMode = .always
        
        return textField
    }()
    
    var passwordTextField: UITextField = {
        let textField = UITextField()
        textField.isSecureTextEntry = true
        textField.placeholder = "请输入6-16位字母/数字密码"
        let imageView = UIImageView(image: UIImage.init(named: "ic_lock")!.withRenderingMode(.alwaysTemplate))
        imageView.tintColor = UIColor.gray
        imageView.frame = CGRect(x: 0, y: 0, width: 38, height: 24)
        imageView.contentMode = .scaleAspectFit
        textField.leftView = imageView
        textField.leftViewMode = .always
        
        return textField
    }()
    
    var nextButton: UIButton = {
        let button = UIButton()
        button.backgroundColor = colorWith255RGB(16, g: 142, b: 233)
        button.setTitle("下一步", for: .normal)
        button.layer.cornerRadius = 6
        button.layer.shadowColor = UIColor.black.cgColor
        button.layer.shadowOpacity = 0.2
        button.layer.shadowOffset = CGSize(width: 1, height: 1)
        
        return button
    }()
    
    var isUserAgree: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()
        self.beenRegister = false
        self.view.backgroundColor = UIColor.white
        
        let firstButton = UIBarButtonItem(image: UIImage.init(named: "ic_keyboard_arrow_left_36pt"), style: .done, target: self, action: #selector(doLeftAction))
        firstButton.tintColor = UIColor.black
        let secondButton = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        secondButton.width = -15
        self.navigationItem.leftBarButtonItems = [firstButton]//secondButton
        
//        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "点击", style: .done, target: self, action: #selector(doRightAction))
        
        self.title = "绑定手机"
        
        self.setupViews()
    }
    
    func doRightAction() {
    }
    
    func setupViews() {
        self.view.addSubview(self.phoneNumberTextField)
        self.phoneNumberTextField.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(15)
            make.right.equalTo(self.view).offset(-15)
            make.top.equalTo(self.view).offset(64)
            make.height.equalTo(50)
        }
        
        let phoneNumberLine = UIView()
        phoneNumberLine.backgroundColor = UIColor.lightGray
        self.view.addSubview(phoneNumberLine)
        phoneNumberLine.snp.makeConstraints { (make) in
            make.top.equalTo(self.phoneNumberTextField.snp.bottom)
            make.right.left.equalTo(self.view)
            make.height.equalTo(0.3)
        }
        
        self.view.addSubview(securityTextField)
        self.securityTextField.snp.makeConstraints { (make) in
            make.top.equalTo(phoneNumberLine.snp.bottom)
            make.left.height.equalTo(self.phoneNumberTextField)
        }
        
        let button = UIButton()
        button.addTarget(self, action: #selector(doCountDownAction(_:)), for: .touchUpInside)
        button.layer.cornerRadius = 10
        button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        button.setTitle("获取验证码", for: .normal)
        button.backgroundColor = colorWith255RGB(16, g: 142, b: 233)
        self.view.addSubview(button)
        button.snp.makeConstraints { (make) in
            make.left.equalTo(self.securityTextField.snp.right)
            make.centerY.equalTo(self.securityTextField)
            make.right.equalTo(self.view).offset(-15)
            make.size.equalTo(CGSize.init(width: 80, height: 30))
        }
        
        let securityFieldLine = UIView()
        securityFieldLine.backgroundColor = UIColor.lightGray
        self.view.addSubview(securityFieldLine)
        securityFieldLine.snp.makeConstraints { (make) in
            make.top.equalTo(self.securityTextField.snp.bottom)
            make.right.left.equalTo(self.view)
            make.height.equalTo(0.7)
        }
        
        self.view.addSubview(self.passwordTextField)
        self.passwordTextField.snp.makeConstraints { (make) in
            make.right.height.left.equalTo(self.phoneNumberTextField)
            make.top.equalTo(securityFieldLine.snp.bottom)
        }
        
        let bottomView = UIView()
        bottomView.backgroundColor = colorWith255RGB(249, g: 249, b: 249)
        self.view.addSubview(bottomView)
        bottomView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalTo(self.view)
            make.top.equalTo(self.passwordTextField.snp.bottom)
        }
        
        let userAgreeLabel = YYLabel()
        bottomView.addSubview(userAgreeLabel)
        userAgreeLabel.snp.makeConstraints { (make) in
            make.left.right.equalTo(bottomView)
            make.top.equalTo(bottomView).offset(15)
        }
        //文
        let hintText = NSMutableAttributedString(string: "我已阅读并同意《姜太公网服务协议》")
        hintText.yy_font = UIFont.systemFont(ofSize: 14)
        hintText.yy_setTextHighlight(NSRange.init(location: 7, length: 10), color: colorWith255RGB(16, g: 142, b: 233), backgroundColor: UIColor.lightGray) { (_, _, _, _) in
            let toWebView = TOWebViewController(urlString: certificationDetailUrl)
            toWebView?.showUrlWhileLoading = false
            toWebView?.showActionButton = false
            toWebView?.showDoneButton = true
            toWebView?.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(toWebView!, animated: true)
        }
        //图
        let imageView = UIImageView(frame:CGRect.init(x: 0, y: 0, width: 17, height: 17))
        imageView.isUserInteractionEnabled = true
    imageView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(doTapUserAgreeAction(_:))))
        imageView.image = UIImage(named: "rent_noSelect")
        let attachAttributed = NSAttributedString.yy_attachmentString(withContent: imageView, contentMode: .scaleAspectFit, attachmentSize: imageView.bounds.size, alignTo: UIFont.systemFont(ofSize: 14), alignment: .center)
        hintText.insert(attachAttributed, at: 0)
        hintText.yy_alignment = .center
        userAgreeLabel.attributedText = hintText
        
        bottomView.addSubview(self.nextButton)
        self.nextButton.addTarget(self, action: #selector(doNextAction), for: .touchUpInside)
        self.nextButton.snp.makeConstraints { (make) in
           make.top.equalTo(userAgreeLabel.snp.bottom).offset(40)
            make.right.equalTo(bottomView).offset(-40)
            make.left.equalTo(bottomView).offset(40)
            make.height.equalTo(40)
        }
        
    }
    
    @objc func doLeftAction(){
        self.dismiss(animated: true, completion: nil)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
    }
    @objc func doCountDownAction(_ button: UIButton) {
        self.phoneNumberTextField.resignFirstResponder()
        guard let phoneNumber = self.phoneNumberTextField.text, phoneNumber.count > 0 else {
            WWError("请输入手机号码后再获取")
            return
        }
        
        guard RegularTool.isValidatePhoneNum(phoneNumber) else {
            WWError("请输入正确的11位手机号码格式")
            return
        }
        
        if self.beenRegister == false{
        
        CommonModel.checkPhoneNumberWithoutToken(phoneNumber, needPhoneExist: false) { (response) in
            if response.success {
                button.startWithTime(60, title: "获取验证码", countDownTitle: "重新发送", mainColor: button.backgroundColor!, countColor: UIColor.gray)
                
                UserModel.requestSecurityCode(phoneNumber: phoneNumber, flag: FlagType.register) { (response) in
                        if response.success {
                            
                            #if DEBUG
                                WWInform(response.value ?? "好像是空的")
                            #else
                            #endif
                            
                        }
                        else
                        {
                            WWError(response.message)
                        }
              }
                
            }
            else {
                if response.message.contains("该手机号码已注册"){
                    
                let keyWindow = UIApplication.shared.keyWindow
                 keyWindow?.addSubview(self.reRegisterView)
                    
                }else{
                WWError(response.message)
                }
            }
        }
        
        }else{
            button.startWithTime(60, title: "获取验证码", countDownTitle: "重新发送", mainColor: button.backgroundColor!, countColor: UIColor.gray)
            UserModel.requestSecurityCode(phoneNumber: phoneNumber, flag: FlagType.agentapply) { (response) in
                if response.success {
                    
                    #if DEBUG
                        WWInform(response.value ?? "好像是空的")
                    #else
                    #endif
                    
                }
                else
                {
                    WWError(response.message)
                }
            }
        }
    }
    @objc fileprivate func reRegisterClick(){
        self.reRegisterView.cancleView()
        self.beenRegister = true
    }
    @objc fileprivate func popButtonClick(){
        self.reRegisterView.cancleView()
        self.dismiss(animated: true) {
            
        }
    }
    @objc func doTapUserAgreeAction(_ sender: UIGestureRecognizer) {
        let view = sender.view as! UIImageView
        self.isUserAgree = (self.isUserAgree == false ? true : false)
        view.image = UIImage(named: isUserAgree ? "rent_selected" : "rent_noSelect")
    }
    
    @objc func doNextAction() {
        guard let phoneNumber = self.phoneNumberTextField.text, phoneNumber.characters.count > 0 else {
            WWError("手机号码是空的")
            return
        }
        guard let varificationCode = self.securityTextField.text, varificationCode.characters.count > 0 else {
            WWError("短信验证码是空的！")
            return
        }
        guard let password = self.passwordTextField.text, password.characters.count > 0 else {
            WWError("密码是空的")
            return
        }
        guard password.range(of: "&") == nil else {
            WWError("密码必须为6-16位字母/数字组合！")
            return 
        }
        guard self.isUserAgree else {
            WWError("是否同意用户协定")
            return
        }
        if self.beenRegister == false{
            WWBeginLoadingWithStatus("开始注册")
            UserModel.register(phoneNumber: phoneNumber, verification: varificationCode, password: password) { (response) in
                if response.success {
                    WWBeginLoadingWithStatus("注册成功开始登录")
                    
                    self.login(phoneNumber, password: password)
                }
                else {
                    
                    WWError(response.message)
                }
            }
            
        }else{
           
            WWBeginLoadingWithStatus("开始注册")
            var parameter = [String:String].init()
            parameter["phoneNumber"] = phoneNumber
            parameter["verifycode"] = varificationCode
            parameter["passWord"] = password
            Alamofire.request(ReRegisterAccountUrl, method: .get, parameters: parameter, headers: nil).responseJSON { (response) in
                if response.result.isSuccess {
                    if let dict = response.result.value as? [String: Any] {
                       
                        guard  dict["State"] as! NSString == "OK" else{
                            return
                        }
                        WWSuccess("注册成功")
                        WWBeginLoadingWithStatus("注册成功开始登录")
                        self.login(phoneNumber, password: password)
                    }
                }else{
                    
                }
            }
        }
    }
    
    func login(_ username: String, password: String) {
        UserModel.login(username: username, password: password) { (response) in
            if response.success {
                WWEndLoading()
                self.present(WWTabBarController(), animated: true, completion: nil)
            }
            else {
                WWError("登录失败")
                self.dismiss(animated: true, completion: nil)
            }
        }
    }

}
